/**
 * 设置cookies
 * @param {*} key 键名
 * @param {*} value 键值
 * @param {*} exdays 保存的天数
 */
export function setCookie(key, value, exdays) {
  if (exdays) {
    // 获取当前时间
    const exdate = new Date();
    exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays);
    // 字符串拼接cookie
    window.document.cookie = `${key}=${value};path=/;expires=${exdate.toGMTString()}`;
  } else {
    window.document.cookie = `${key}=${value};path=/;`;
  }
}

/**
 * 获取cookies
 * @param {*} key
 * @returns string
 */
export function getCookie(key) {
  if (window.document.cookie.length > 0) {
    const arr = document.cookie.split(";");
    for (let i = 0; i < arr.length; i++) {
      // 再次切割
      const arr2 = arr[i].split("=");
      // 判断查找相对应的值
      const cookieKey = arr2[0];
      if (
        cookieKey &&
        typeof cookieKey === "string" &&
        cookieKey.trim() === key
      ) {
        return arr2[1];
      }
    }
  }
  return null;
}
